package com.lcgroup.springdemo.demos.filter;

import com.alibaba.fastjson.JSON;
import com.lcgroup.springdemo.demos.handler.GlobeExceptionHandler;
import com.lcgroup.springdemo.demos.bean.ResultResponse;
import com.lcgroup.springdemo.demos.bean.ZSException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@RequiredArgsConstructor
@Slf4j
public class GlobeFilter extends OncePerRequestFilter {

    private final GlobeExceptionHandler globeExceptionHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("进入过滤器doFilterInternal");
        String filter = request.getHeader("filter");
        if (filter != null && filter.equals("1")){
            filterChain.doFilter(request, response);
        }else {
            ResultResponse<String> stringResultResponse = globeExceptionHandler.handleException(new ZSException("过滤器报错"));
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSON.toJSONString(stringResultResponse));
//            throw new ZSException("过滤器报错");

        }
    }
}


